from flask.helpers import make_response
import pika
from pika.channel import Channel
from ..tools.images.wordcloud import WordCloudGenerator
from ..tools.images.watermark import WaterMark
from ..tools.images.ocr import OCRModel
from . import api
from flask import json, request, jsonify
from app import connet_parameter
from app import redis_client
from uuid import uuid4
from app import executor


def send_asyn_rabbit(exchange, routing_key, body):
    # 初始化Rabbit生产者
    connection = pika.BlockingConnection(connet_parameter)
    channel: Channel = connection.channel()
    channel.basic_publish(exchange=exchange,
                          routing_key=routing_key,
                          body=json.dumps(body))
    channel.close()


# 获取水印
@api.route('/images/wordcloud', methods=['POST'])
def image_wordcloud():
    data = request.json
    identifier = uuid4().hex
    data['identifier'] = identifier
    executor.submit(send_asyn_rabbit, 'pytools.system.direct', 'wordcloud',
                    data)
    return jsonify(identifier=identifier)

# 请求图片
@api.route('/images/<uuid>', methods=['GET'])
def image_result(uuid):
    IMAGE_PREFIX = 'pytools:image:'
    result = redis_client.get(IMAGE_PREFIX + uuid)
    if result is None:
        return jsonify(status=1)
    return jsonify(status=0, image=result.decode('utf-8'))

# 添加水印
@api.route('/images/watermarker', methods=['POST'])
def image_watermaker():
    data = request.json
    identifier = uuid4().hex
    data['identifier'] = identifier
    executor.submit(send_asyn_rabbit, 'pytools.system.direct', 'watermarker',
                    data)
    return jsonify(identifier=identifier)

# 请求OCR接口
@api.route('/images/ocr', methods=['POST'])
def image_ocr():
    data = request.json
    identifier = uuid4().hex
    data['identifier'] = identifier
    executor.submit(send_asyn_rabbit, 'pytools.system.direct', 'ocr',
                    data)
    return jsonify(identifier=identifier)


def args_converter(args):
    if args.get('space'):
        args['space'] = int(args['space'])
    if args.get('opacity'):
        args['opacity'] = int(args['opacity'])
    if args.get('angle'):
        args['angle'] = int(args['angle'])
    if args.get('txtsize'):
        args['txtsize'] = int(args['txtsize'])
    if args.get('height'):
        args['height'] = int(args['height'])
    if args.get('quality'):
        args['quality'] = int(args['quality'])
    return args
